<template>
  <div class="login-container">
    <div class="logo" />
    <div class="form">
      <div class="login">
        <h1>{{title}}</h1>
        <el-card shadow="never" class="login-card">
          <!--登录表单-->
          <el-form ref="form" :model="loginForm" :rules="loginRules" v-show="!loginType">
            <el-form-item prop="mobile">
              <el-input v-model="loginForm.mobile" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="loginForm.password" placeholder="请输入密码" show-password />
            </el-form-item>
            <el-form-item>
              <div id="vefCode" />
            </el-form-item>
            <el-form-item prop="isAgree">
              <el-checkbox v-model="loginForm.isAgree">用户平台协议</el-checkbox>
            </el-form-item>
            <el-form-item>
              <el-button style="width:350px" type="primary" @click="login">登录</el-button>
            </el-form-item>
          </el-form>
          <img :src="qrCodeSrc" v-show="loginType" alt="扫码登录二维码">
          <div class="toggle">
            <span class="byMobile" @click="loginToggle">手机号登录</span>
            <div class="gap"></div>
            <span class="qrCode" @click="loginToggle">扫码登录</span>
          </div>
        </el-card>
        <button class="qq"><img src="@/assets/qq.svg" alt=""></button>
      </div>
    </div>
  </div>
</template>
<script>
/* global initGeetest4 */
import '@/utils/gt4.js'; // 引入验证脚本
import { _getQrcodeKey, _getQrcodeState } from '@/api/user';
import QRCode from 'qrcode';

export default {
  name: 'Login',
  data() {
    return {
      today: null,
      title: '手机号登录',
      loginType: 0,
      qrCodeSrc: null,
      qrTimer: null,
      scanStatus: null,
      loginForm: {
        mobile: process.env.NODE_ENV === 'development' ? '13800000002' : '',
        password: '',
        isAgree: process.env.NODE_ENV === 'development',
      },

      loginRules: {
        mobile: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur', // 失去焦点
          },
          {
            pattern: /^1[3~9]\d{9}$/,
            message: '手机号格式不正确',
            trigger: 'blur',
          },
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur',
          },
          {
            min: 6,
            max: 20,
            message: '密码长度应为6位到20位',
            trigger: 'blur',
          },
        ],
        isAgree: [
          {
            validator: (rule, value, callback) => {
              // rule 校验规则
              // value 校验的值
              // callback 函数 - 类似promise resolve reject,无论校验结果如何必须调用这个函数
              // callback() 表示校验通过
              // callback(new Error(错误信息)) 表示校验失败,并删除错误信息
              value ? callback() : callback(new Error('用户协议未勾选'));
            },
          },
        ],
      },
    };
  },
  created() {
    console.log(this.getCurrentMonthDay());
    this.today = this.getCurrentMonthDay();
    console.log(this.today);
    // 开发环境下拼接密码
    if (process.env.NODE_ENV === 'development') {
      this.loginForm.password = 'itHeiMa@2025' + this.today;
      console.log('开发环境密码:', this.loginForm.password); // 确认输出 itHeiMa@20250724
    }

    initGeetest4(
      {
        captchaId: 'e1ef8c20d0c13488feef42c5c7973e54',
        product: 'popup', // 验证展示形式
      },
      function (captcha) {
        // captcha为验证码实例
        captcha.appendTo('#vefCode'); // 调用appendTo将验证码插入到页的某一个元素中，这个元素用户可以自定义
      }
    );
  },
  methods: {
    getCurrentMonthDay() {
      const date = new Date();
      // 获取月份（0-11，需+1）并补零
      const month = String(date.getMonth() + 1).padStart(2, '0');
      // 获取日期并补零
      const day = String(date.getDate() - 1).padStart(2, '0');
      // 拼接为 MMDD 格式
      return month + day;
    },
    login() {
      // 通过事件再次对整个表单进行校验的方法validate
      this.$refs.form.validate(async isValid => {
        if (isValid) {
          // alert('校验通过')
          await this.$store.dispatch('user/login', this.loginForm);
          this.$router.push('/');
        }
      });
    },
    async loginToggle(e) {
      if (e.target.innerHTML === '手机号登录') {
        this.title = '手机号登录';
        this.loginType = 0;
        clearInterval(this.qrTimer); // 切换回手机号登录时，清除定时器
      } else {
        this.title = '扫码登录';
        this.loginType = 1;
        try {
          // 获取二维码密钥
          const res = await _getQrcodeKey();
          console.log('获取二维码成功:', res);

          // 生成二维码
          QRCode.toDataURL(res, (err, url) => {
            if (err) return console.error('生成二维码失败:', err);
            this.qrCodeSrc = url;
          });

          // 开始轮询扫码状态
          let timer = setInterval(async () => {
            try {
              const data = await _getQrcodeState(res);
              console.log('扫码状态:', data.codeState);

              switch (data.codeState) {
                case 1: // 用户未扫码但加密串正常
                  // 继续等待，不做处理
                  break;

                case 2: // 用户已扫码但未点击登录
                  // 可显示提示："请在手机上确认登录"
                  this.scanStatus = '已扫码，请确认';
                  break;

                case 3: // 扫码登录成功
                  clearInterval(timer); // 清除定时器
                  this.$store.commit('setUserToken', data.token); // 存储登录状态
                  this.$router.push('/'); // 跳转到首页
                  break;

                case 4: // 二维码已失效
                  clearInterval(timer); // 清除定时器
                  this.scanStatus = '二维码已过期';
                  // 重新生成二维码或提示用户刷新
                  setTimeout(() => this.loginToggle(e), 2000); // 2秒后自动刷新
                  break;

                case 5: // 用户取消登录
                  clearInterval(timer); // 清除定时器
                  this.scanStatus = '已取消登录';
                  // 可恢复到初始状态或提示用户重新扫码
                  break;

                default:
                  console.warn('未知状态码:', codeState);
              }
            } catch (error) {
              console.error('获取扫码状态失败:', error);
              // 出错时可选择重试或提示用户
            }
          }, 2000); // 每2秒检查一次

          // 保存定时器引用，用于组件销毁时清除
          this.qrTimer = timer;
        } catch (error) {
          console.error('获取二维码失败:', error);
          // 提示用户重新尝试
        }
      }
    },
  },
};
</script>
<style lang="scss">
.login-container {
  display: flex;
  align-items: stretch;
  height: 100vh;
  .logo {
    flex: 1;
    background: rgba(38, 72, 176) url(~@/assets/background_pic/blueBoat.png) no-repeat center /
      cover;
    border-top-right-radius: 60px;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    justify-content: center;
    padding: 0 100px;
    .icon {
      background: url(../../assets/common/logo.png) no-repeat 70px center / contain;
      width: 300px;
      height: 50px;
      margin-bottom: 50px;
    }
    p {
      color: #fff;
      font-size: 18px;
      margin-top: 20px;
      width: 300px;
      text-align: center;
    }
  }
  .form {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    .login {
      width: 450px;
      // margin: 0 auto;
      box-sizing: border-box;
      border: 1px solid #eee;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      padding: 30px;
      .el-card {
        // width: 100%;
        border: none;
        padding: 0;
        .toggle {
          display: flex;
          align-items: center;
          width: 100%;
          text-align: center;
          font-size: 12px;
          font-weight: 500;
          color: rgb(96, 98, 102);
          span:nth-child(odd) {
            flex: 5;
            border: 1px solid #eee;
            padding: 10px 0;
            cursor: pointer;
          }
          span:nth-child(odd):hover {
            background-color: #edf5ff;
            color: #529cfe;
            border: 1px solid #b1cdfe;
          }
          .gap {
            flex: 1;
          }
        }
      }
      .qq {
        margin: 0 auto;
      }
      h1 {
        padding-left: 20px;
        align-self: flex-start;
        font-size: 24px;
      }
      .el-input {
        width: 350px;
        height: 44px;
        .el-input__inner {
          background: #f4f5fb;
        }
      }
      .el-checkbox {
        color: #606266;
      }
    }
  }
}
</style>
